package xyz.liut.citypicker;

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.LinearLayout;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import xyz.liut.citypicker.adapters.ArrayWheelAdapter;
import xyz.liut.liutlibrarys.R;

/**
 * Created by liut_ on 2016/3/31.
 */
public class CityPicker extends LinearLayout implements OnWheelChangedListener {


    private static final String TAG = "CityPicker";
    private JSONObject mJsonObj;
    private WheelView mProvince;
    private WheelView mCity;
    private WheelView mArea;

    private String[] mProvinceDatas;
    private Map<String, String[]> mCitisDatasMap = new HashMap<>();
    private Map<String, String[]> mAreaDatasMap = new HashMap<>();

    private String mCurrentProviceName;
    private String mCurrentCityName;
    private String mCurrentAreaName;

    public CityPicker(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView(context);
    }

    public CityPicker(Context context) {
        super(context);
        initView(context);
    }

    public CityPicker(Context context, AttributeSet attrs) {
        super(context, attrs);
        initView(context);
    }

    private void initView(Context context) {
        if (isInEditMode()) {
            return;
        }
        View.inflate(context, R.layout.citypicker, this);
        mCurrentCityName = "";
        mCurrentAreaName = "";

        initJsonData();

        mProvince = (WheelView) findViewById(R.id.id_province);
        mCity = (WheelView) findViewById(R.id.id_city);
        mArea = (WheelView) findViewById(R.id.id_area);

        initDatas();

        mProvince.setViewAdapter(new ArrayWheelAdapter<>(context, mProvinceDatas));
        mProvince.addChangingListener(this);
        mCity.addChangingListener(this);
        mArea.addChangingListener(this);

//        mProvince.setVisibleItems(5);
//        mCity.setVisibleItems(7);
//        mArea.setVisibleItems(5);

        updateCities();
        updateAreas();
    }


    private void updateAreas() {
        int pCurrent = mCity.getCurrentItem();
        mCurrentCityName = mCitisDatasMap.get(mCurrentProviceName) == null ? "" : mCitisDatasMap.get(mCurrentProviceName)[pCurrent];
        if (listener != null) {
            listener.onCity(mCurrentCityName);
        }
        String[] areas = mAreaDatasMap.get(mCurrentCityName);

        if (areas == null) {
            areas = new String[]{""};
        }
        mArea.setViewAdapter(new ArrayWheelAdapter<>(getContext(), areas));
        mArea.setCurrentItem(0);
    }

    private void updateCities() {
        int pCurrent = mProvince.getCurrentItem();
        mCurrentProviceName = mProvinceDatas[pCurrent];
        if (listener != null) {
            listener.onProvice(mCurrentProviceName);
        }
        String[] cities = mCitisDatasMap.get(mCurrentProviceName);
        if (cities == null) {
            cities = new String[]{""};
        }
        mCity.setViewAdapter(new ArrayWheelAdapter<String>(getContext(), cities));
        mCity.setCurrentItem(0);
        updateAreas();
    }

    private void initJsonData() {
        StringBuilder sb = new StringBuilder();
        InputStream is = null;
        try {
            is = getClass().getClassLoader().getResourceAsStream("assets/city.json");

            int len = -1;
            byte[] buf = new byte[1024];
            while ((len = is.read(buf)) != -1) {
                sb.append(new String(buf, 0, len, "utf-8"));
            }
            mJsonObj = new JSONObject(sb.toString());
        } catch (IOException | JSONException e) {
            e.printStackTrace();
        } finally {
            try {
                if (is != null)
                    is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    private void initDatas() {
        try {
            JSONArray jsonArray = mJsonObj.getJSONArray("citylist");
            mProvinceDatas = new String[jsonArray.length()];
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jsonP = jsonArray.getJSONObject(i);
                String province = jsonP.getString("p");

                mProvinceDatas[i] = province;

                JSONArray jsonCs = null;
                try {
                    jsonCs = jsonP.getJSONArray("c");
                } catch (Exception e1) {
                    continue;
                }
                String[] mCitiesDatas = new String[jsonCs.length()];
                for (int j = 0; j < jsonCs.length(); j++) {
                    JSONObject jsonCity = jsonCs.getJSONObject(j);
                    String city = jsonCity.getString("n");
                    mCitiesDatas[j] = city;
                    JSONArray jsonAreas = null;
                    try {
                        jsonAreas = jsonCity.getJSONArray("a");
                    } catch (Exception e) {
                        continue;
                    }

                    String[] mAreasDatas = new String[jsonAreas.length()];
                    for (int k = 0; k < jsonAreas.length(); k++) {
                        String area = jsonAreas.getJSONObject(k).getString("s");
                        mAreasDatas[k] = area;
                    }
                    mAreaDatasMap.put(city, mAreasDatas);
                }

                mCitisDatasMap.put(province, mCitiesDatas);
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }
        mJsonObj = null;
    }


    @Override
    public void onChanged(WheelView wheel, int oldValue, int newValue) {
        if (wheel == mProvince) {
            updateCities();
            mCurrentAreaName = mAreaDatasMap.get(mCurrentCityName) == null ? "" : mAreaDatasMap.get(mCurrentCityName)[0];
            if (listener != null) {
                listener.onArea(mCurrentAreaName);
            }
        } else if (wheel == mCity) {
            updateAreas();
            mCurrentAreaName = mAreaDatasMap.get(mCurrentCityName) == null ? "" : mAreaDatasMap.get(mCurrentCityName)[0];
            if (listener != null) {
                listener.onArea(mCurrentAreaName);
            }
        } else if (wheel == mArea) {
            mCurrentAreaName = mAreaDatasMap.get(mCurrentCityName)[newValue];
            if (listener != null) {
                listener.onArea(mCurrentAreaName);
            }
        }
    }

    public List<String> getChoose() {
        List<String> city = new ArrayList<>();
        city.add(mCurrentProviceName);
        city.add(mCurrentCityName);
        city.add(mCurrentAreaName);
        return city;
    }

    public interface OnCityPickerChangedListener {
        void onProvice(String provice);

        void onCity(String city);

        void onArea(String area);
    }

    private OnCityPickerChangedListener listener;

    public void setOnCityChangeListener(OnCityPickerChangedListener listener) {
        this.listener = listener;
    }

}
